﻿using System;
using System.Collections.Generic;
using System.Text;
using EnvDTE;
using EnvDTE80;
using System.IO;

namespace RunVistaGadget31.AdditionalApplicationsWrappers
{
    /// <summary>
    /// 
    /// </summary>
    public class GadgetRunner : ApplicationRunner
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="applicationObject"></param>
        public GadgetRunner(DTE2 applicationObject)
            : base(applicationObject, false)
        {

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="applicationObject"></param>
        /// <param name="isRunAsWinApp"></param>
        public GadgetRunner(DTE2 applicationObject, bool isRunAsWinApp)
            : base(applicationObject, isRunAsWinApp)
        {

        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public override string GetAppArguments()
        {

            String GadgetArgs = " shell32.dll,ShellExec_RunDLL " + GadgetPath;
            return GadgetArgs;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public override string GetOutputAndRunApplication()
        {

            base.CalledApplicationPath = "rundll32.exe";
            CleanPreviousGadget();
            return base.GetOutputAndRunApplication();
        }
        private void CleanPreviousGadget()
        {
            string GadgetName = Path.GetFileName(this.GadgetPath.Replace("\"", ""));
            string GadgetStoreDirectoryName = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + @"\Microsoft\Windows Sidebar\Gadgets\";
            string FullGadgetStorePath = GadgetStoreDirectoryName + GadgetName;
            try
            {

                string[] GadgetDirectories = Directory.GetDirectories(GadgetStoreDirectoryName, GadgetName + "*");
                foreach (string dir in GadgetDirectories)
                {

                    Directory.Delete(dir, true);
                    System.Threading.Thread.Sleep(500);
                }

            }
            catch (System.IO.IOException e)
            {
                throw;
            }
        }

    }
}
